module utils.MyJwt;

import vibe.http.server : HTTPServerRequest, HTTPServerResponse;
import vibe.data.json : Json, parseJsonString;
import fastjwt.jwt;
import stringbuffer;
import utils.ConstValue : Const;
import utils.RespData : RespData;

/** 
 * 生成token
 * Params:
 *   userData = 用户信息
 */
string createToken (Json userData)
{
    import std.format : format;

    StringBuffer buf;
    encodeJWTToken(buf, JWTAlgorithm.HS256, Const.jwtSecretStr, userData);

    string token = format("%s", buf.getData!string());
    return token;
}

/** 
 * 验证token
 */
void jwtValidator (HTTPServerRequest req, HTTPServerResponse resp)
{
    import std.algorithm.searching : startsWith;
    import std.datetime.systime : Clock;

    string authStr = "Authorization";
    string bearer = "Bearer ";

    if (authStr !in req.headers || !req.headers[authStr].startsWith(bearer))
    {
        resp.writeJsonBody(RespData.newData(401, "请登录"), 401);
        return;
    }

    StringBuffer header;
    StringBuffer payload;

    const result = decodeJWTToken(req.headers[authStr][bearer.length .. $],
        Const.jwtSecretStr, JWTAlgorithm.HS256, header, payload);
    if (result > 0)
    {
        resp.writeJsonBody(RespData.newData(401, "token不正确"), 401);
        return;
    }
    Json pdata = parseJsonString(payload.getData());
    if (pdata["exp"].type() != Json.Type.undefined)
    {
        long exp = pdata["exp"].to!long();
        long now = Clock.currTime.toUnixTime();
        if (exp <= now)
        {
            resp.writeJsonBody(RespData.newData(401, "token已过期"), 401);
            return;
        }
    }
}
